﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;

public partial class User_ReplyMailBox : System.Web.UI.Page
{
    UserMailbox MailRepo = new UserMailbox();
    UsersRepository URepo = new UsersRepository();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            int MailId = int.Parse(Request.QueryString["MailID"]);
            if (MailId > 0)
            {
                var a = MailRepo.GetReplyMail(MailId);
                if (a != null)
                {
                    txtSubject.Text = (a.MailBox_Subject.Contains("RE:")) ? a.MailBox_Subject.Trim() : "RE: " + a.MailBox_Subject.Trim();
                    txtReceiver.Text = URepo.GetEmailById((int)a.Users_Id);
                    CKEditorControl1.Text = a.MailBox_Content;
                    hdfparentmsg.Value = a.MailBox_ParentId.ToString();
                }
                else
                    Response.Redirect(ResolveUrl("~/Mailbox.html"));
            }
            else
                Response.Redirect(ResolveUrl("~/Mailbox.html"));
        }
        catch
        {
            Response.Redirect(ResolveUrl("~/Mailbox.html"));
        }
    }

    protected void btnReply_Click(object sender, EventArgs e)
    {
        try
        {
            ReplyMail();
            ExtNet.Msg.Alert("Reply", "Đã gửi thư thành công");
            Response.Redirect(ResolveUrl("~/Mailbox.html"));
        }
        catch
        {
            Response.Redirect(ResolveUrl("~/Mailbox.html"));
        }
    }

    public void ReplyMail()
    {
        HttpCookie _user = Request.Cookies["userinfo"];
        int userId = 0;
        if (Request.Cookies["userinfo"] != null)
        {
            if (_user["username"] != null)
            {
                userId = URepo.GetUserIdByName(_user["username"]);
            }
        }
        int receiverId = URepo.GetIdByEmailOrUsername(txtReceiver.Text);
        string SenderEmail = URepo.GetEmailById(userId);
        MailRepo.ReplyMail(userId, txtSubject.Text, CKEditorControl1.Text, userId, (int)Mailbox.unread, (int)Mailbox.Outbox, DateTime.Now, SenderEmail, DateTime.Now, int.Parse(hdfparentmsg.Value));
    }
}